package com.yaowk.sfp.security;

import com.yaowk.sfp.system.api.model.Resource;
import com.yaowk.sfp.system.server.service.IResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 资源权限初始化与获取
 */
@Service
public class SystemInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IResourceService resourceService;

    /**
     * 匹配资源权限
     *
     * @throws IllegalArgumentException
     * @8;aaaa44EH/。， return
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation) o;
        List<Resource> all = resourceService.findAll();
        for (Resource resource : all) {
            try {
                HttpMethod.resolve(resource.getMethod());
            } catch (Exception e) {
                continue;
            }
            RequestMatcher requestMatcher = new AntPathRequestMatcher(resource.getResource(), resource.getMethod());
            if (requestMatcher.matches(filterInvocation.getHttpRequest())) {
                List<ConfigAttribute> attributes = new ArrayList<>();
                attributes.add(new SecurityConfig(resource.getId().toString()));
                return attributes;
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return new ArrayList<>();
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
